package com.ruizhong.centercontroll.util;

import java.io.IOException;
import java.net.*;
import java.util.concurrent.*;

public class UDPSender {
    private static ExecutorService executor = Executors.newSingleThreadExecutor();

    public static String send(String aimIpAddress, Integer aimPort, byte[] message, Boolean needReply) {

        try (final DatagramSocket socket = new DatagramSocket()) {
            // 创建DatagramSocket实例（可选地可以指定端口号，如果不指定则系统会自动分配一个）  

            // 目标IP地址和端口号  
            String hostname = aimIpAddress; // 或者使用IP地址，如 "127.0.0.1"
            int port = aimPort; // 目标端口号
            // 将目标IP地址转换为InetAddress对象  
            InetAddress addr = InetAddress.getByName(hostname);

            // 创建DatagramPacket实例，指定数据和目标地址  
            DatagramPacket packet = new DatagramPacket(message, message.length, addr, port);
            // 发送数据包  
            socket.send(packet);
            System.out.println("Message sent: " + message);
            String response = null;
            if (needReply) {
                Future<String> futureResponse = executor.submit(() -> {
                    byte[] receiveData = new byte[1024];
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    socket.receive(receivePacket);
                    return new String(receivePacket.getData(), 0, receivePacket.getLength());
                });
                try {
                    // 尝试在1秒内获取接收结果
                    response = futureResponse.get(1, TimeUnit.SECONDS);
                    if (response != null) {
                        System.out.println("Received response: " + response);
                    } else {
                        System.out.println("No response received or an error occurred.");
                    }
                } catch (TimeoutException e) {
                    System.out.println("Timeout occurred. No response received within 1 second.");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 取消Future（尽管在这个例子中它可能已经被完成了）
                    futureResponse.cancel(false);

                }
            }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    public static String sendInBoardCast(String aimIpAddress, Integer aimPort, byte[] message) {
        DatagramSocket socket = null;
        try {
            // 创建一个DatagramSocket实例，并设置其广播标志为true
            socket = new DatagramSocket();
            socket.setBroadcast(true);


            // 获取广播地址的InetAddress实例
            InetAddress broadcastAddr = InetAddress.getByName(aimIpAddress);

            // 创建一个DatagramPacket实例，包含要发送的数据、数据长度、目标地址和端口
            DatagramPacket packet = new DatagramPacket(message, message.length, broadcastAddr, aimPort);

            // 发送数据包
            socket.send(packet);
            System.out.println("Broadcast message sent: " + message);

        } catch (SocketException e) {
            System.err.println("Socket error: " + e.getMessage());
        } catch (UnknownHostException e) {
            System.err.println("Unknown host: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("IO error: " + e.getMessage());
        } finally {
            // 确保在完成后关闭套接字
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        }
        return null;
    }

    public static String sendInGroup(String aimIpAddress, Integer aimPort, byte[] message, Boolean needReply) {
        try {
            // 创建DatagramSocket并绑定到组播地址和端口（可选）
            DatagramSocket socket = new DatagramSocket();
            socket.setBroadcast(true); // 设置为广播模式（对于组播也是必要的）

            // 将组播地址转换为InetAddress对象
            InetAddress group = InetAddress.getByName(aimIpAddress);


            DatagramPacket packet = new DatagramPacket(message, message.length, group, aimPort);

            // 发送数据包
            socket.send(packet);

            System.out.println("Message sent: " + message);

            // 关闭socket
            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void wakeUp(String macAddress, String ipAddress) {
        try {

            byte[] macBytes = getMacAddressBytes(macAddress);
            byte[] packet = new byte[6 + 16 * macBytes.length];

            for (int i = 0; i < 6; i++) {
                packet[i] = (byte) 0xFF;
            }

            for (int i = 1; i <= 16; i++) {
                for (int j = 0; j < macBytes.length; j++) {
                    packet[i * macBytes.length + j] = macBytes[j];
                }
            }

            InetAddress address = InetAddress.getByName(ipAddress); // 通常是广播地址
            DatagramPacket datagramPacket = new DatagramPacket(packet, packet.length, address, 9);
            DatagramSocket socket = new DatagramSocket();
            socket.send(datagramPacket);
            socket.close();
            System.out.println("魔术包已发送！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static byte[] getMacAddressBytes(String macAddress) {
        byte[] bytes = new byte[6];
        String[] hex = macAddress.split("(:|-)");
        for (int i = 0; i < 6; i++) {
            int value = Integer.parseInt(hex[i], 16);
            bytes[i] = (byte) value;
        }
        return bytes;
    }
}